from django.shortcuts import render

# Create your views here.

import logging
import random
import json
import re

from django.views import View
from django_redis import get_redis_connection
from apps.users.models import User
from libs.captcha.captcha import captcha
from django.http.response import HttpResponse, JsonResponse
from celery_tasks.sms.tasks import celery_send_sms_code
from django.contrib.auth import login, authenticate, logout

logger = logging.getLogger('django')


# 图形验证码
class ImageCodeView(View):
    def get(self, request):
        cur = request.GET.get('cur')
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % cur, 300, text)
        return HttpResponse(image, content_type='text/html')


# 短信验证码
class SMSCodeView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        image_code = data.get('text')
        id = data.get('id')
        if not re.match(r'^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$',mobile):
            return JsonResponse({'errno': 400, 'errmsg': '手机号不符合规范'})
        try:
            usemobile = User.objects.get(mobile=mobile)
        except Exception:
            usemobile = ''
        if not all([mobile, image_code]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数'})
        if usemobile:
            return JsonResponse({'errno': 400, 'errmsg': '手机号已存在，注册失败!'})
        redis_conn = get_redis_connection('code')
        image_code_server = redis_conn.get('img_%s' % id)
        if image_code_server is None:
            return JsonResponse({'errno': 400, 'errmsg': '图片验证码失效'})
        try:
            redis_conn.delete('img_%s' % id)
        except Exception as e:
            logger.error(e)
        image_code_server = image_code_server.decode()
        if image_code.lower() != image_code_server.lower():
            return JsonResponse({'errno': 400, 'errmsg': '输入图形验证码有误'})
        sms_code = '%06d' % random.randint(0, 999999)
        redis_conn.setex('sms_%s' % mobile, 300, sms_code)
        celery_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'errno': 0, 'errmsg': '发送成功'})


# 注册
class RegisterView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        phonecode = data.get('phonecode')
        password = data.get('password')
        if not all([mobile, password]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数!'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400, 'errmsg': 'mobile格式有误!'})
        if not re.match(r'^[0-9a-zA-Z]{8,20}$', password):
            return JsonResponse({'errno': 400, 'errmsg': 'password格式有误!'})
        redis_cli = get_redis_connection('code')
        sms_code_server = redis_cli.get('sms_%s' % mobile)
        if not sms_code_server:
            return JsonResponse({'errno': 400, 'errmsg': '短信验证码失效'})
        if phonecode != sms_code_server.decode():
            return JsonResponse({'errno': 400, 'errmsg': '短信验证码有误'})
        try:
            user = User.objects.create_user(
                username=mobile,
                password=password,
                mobile=mobile
            )
        except Exception:
            return JsonResponse({'注册失败!'})
        login(request, user)
        return JsonResponse({'errno': 0, 'errmsg': '注册成功!'})


# 登录
class LoginView(View):
    def post(self, request):
        data = json.loads(request.body.decode())
        username = data.get('mobile')
        password = data.get('password')
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        if not all([username, password]):
            return JsonResponse({'errno': 400, 'errmsg': '缺少必传参数!'})
        user = authenticate(request,username=username, password=password)
        if user is None:
            return JsonResponse({'errno': 400, 'errmsg': '用户名或密码输入错误!'})
        login(request, user)
        request.session.set_expiry(None)
        return JsonResponse({'errno': 0, 'errmsg': '登录成功!'})


    def get(self, request):
        if request.user.is_authenticated:

            username = request.user.username
            user_id = request.user.id
            mobile = request.user.mobile
            response = JsonResponse({'errno': 0, 'errmsg': '已登录', 'data': {'name': username,'user_id':user_id}})
            response.set_cookie('name', mobile, max_age=14 * 24 * 3600)
            return response
        else:
            return JsonResponse({'errno': 4101, 'errmsg': '未登录'})


    def delete(self, request):
        logout(request)
        response = JsonResponse({'errno': 0, 'errmsg': '已退出'})
        response.delete_cookie('name')
        return response
